package com.bw.task.fragment;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bw.task.App;
import com.bw.task.R;
import com.bw.task.activity.PayActivity;
import com.bw.task.activity.SearchAct;
import com.bw.task.adapter.MyViewpagerAdapter;
import com.bw.task.db.DaoMaster;
import com.bw.task.db.DaoSession;
import com.bw.task.db.User;
import com.bw.task.db.UserDao;
import com.bw.task.fragment.onefragment.Fragment1;
import com.bw.task.fragment.onefragment.Fragment2;
import com.bw.task.fragment.onefragment.Fragment3;
import com.bw.task.user.login.LoginActivity;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.frame.lib_common.slidingmenu.SlidingMenu;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;


public class OneFragment extends Fragment {


    private TextView oneLog;
    private ImageView oneImg;
    private SlidingTabLayout slidingTab;
    private ViewPager vpone;
    ArrayList<Fragment> fragments;
    ArrayList<String> strings;
    SharedPreferences user;
    //侧拉
    static SlidingMenu slidingMenu;
    TextView money;
    float slidmoney = 0.00f;
    boolean isEvent = true;
    static SharedPreferences.Editor edit;
    DaoSession daoSession;
    UserDao userDao;
    static ImageView slidimg;


    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what==200){
                LogUtils.i("-----123");
                String obj = (String) msg.obj;
                edit.putString("imgtx",obj);
                edit.commit();
                slidimg.setImageBitmap(BitmapFactory.decodeFile(obj));

            }
        }
    };
    Handler handler1 =new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
                 if (msg.what == 100) {

                     edit = user.edit();
                     float obj = (float) msg.obj;
                     // float a=Float.parseFloat(df);
//                    String s1 = msg.obj.toString();
//                    float v = Float.parseFloat(s1);
//                    slidmoney += v;
//                    edit.putString("money",slidmoney+"");
//                    edit.commit();

                    money.setText(obj + "   余额");
            }
        }
    };
    private ImageView search;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_one, container, false);
        /**
         *  数据库
         */
        DaoMaster.DevOpenHelper users = new DaoMaster.DevOpenHelper(getContext(), "usera");
        SQLiteDatabase writableDatabase = users.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        daoSession = daoMaster.newSession();
        userDao = daoSession.getUserDao();



        oneLog = (TextView) inflate.findViewById(R.id.one_log);
        oneImg = (ImageView) inflate.findViewById(R.id.one_img);
        slidingTab = (SlidingTabLayout) inflate.findViewById(R.id.slidingTab);
        vpone = (ViewPager) inflate.findViewById(R.id.vpone);
        search = (ImageView) inflate.findViewById(R.id.search);
        /**
         * SP存储
         */
        this.user = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        edit = user.edit();
        edit.putString("money",slidmoney+"");
        edit.commit();





        /**
         * 点击搜索
         */
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getContext(), SearchAct.class));
            }
        });
        //注册一次性广播
        if (isEvent){
            EventBus.getDefault().register(OneFragment.this);
        }
        isEvent=false;

//        android:visibility="invisible"
//        oneLog.setVisibility(View.INVISIBLE);


        //判断用户是否登录
        boolean isuser = this.user.getBoolean("isuser", false);
        if (isuser) {
            oneLog.setVisibility(View.INVISIBLE);
            oneImg.setImageResource(R.drawable.gd);
            initSlidingMenu();

            oneImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    slidingMenu.showMenu();
                }
            });
        } else {
            oneLog.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LogUtils.i("登录");
                    ToastUtils.showShort("登录");
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    getActivity().startActivity(intent);
                }
            });
        }


        fragments = new ArrayList<>();
        fragments.add(new Fragment1());
        fragments.add(new Fragment2());
        fragments.add(new Fragment3());

        strings = new ArrayList<>();
        strings.add("关注");
        strings.add("同城");
        strings.add("推荐");


        MyViewpagerAdapter myViewpagerAdapter = new MyViewpagerAdapter(getActivity().getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, fragments);
        vpone.setAdapter(myViewpagerAdapter);

        slidingTab.setViewPager(vpone, strings.toArray(new String[strings.size()]));
        slidingTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {

            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        return inflate;
    }

    @Subscribe(sticky = true)
    public void ever(String msg) {

        String userid = user.getString("userid", "");
        List<User> users = userDao.queryRaw("where userid=?", userid);
        float money = users.get(0).getMoney();
        LogUtils.i("广播money"+money);

        String[] split = msg.split(":");
        String s = split[1];
        if (split[0].equals("ZFB")) {
            LogUtils.i("支付宝返回值" + s);
            Message obtain = Message.obtain();
            obtain.what = 100;
            obtain.obj = money;
            handler1.sendMessage(obtain);
        }
        EventBus.getDefault().removeStickyEvent(msg);
    }

    public void initSlidingMenu() {
        String name = user.getString("name", "");
        /**
         * 获取钱数
         */
        String uid = user.getString("userid", "");
        LogUtils.i("-----获取钱数id"+uid);
        List<User> susers = userDao.queryRaw("where userid=?", uid);
        LogUtils.i(susers.size()+"**********");



        List<User> users = userDao.loadAll();
        for (int i = 0; i < users.size(); i++) {
            LogUtils.i("slide数据库查询----"+"ID:"+users.get(i).getId()+"--name:"+users.get(i).getName()+"--pass:"+users.get(i).getPass()+"--mID:"+users.get(i).getUserid()+"--money:"+users.get(i).getMoney());
        }
        String name1 = susers.get(0).getName();
        Float fmoney = susers.get(0).getMoney();

        slidingMenu = new SlidingMenu(getContext());
        slidingMenu.setBehindWidth(800);
        slidingMenu.attachToActivity(getActivity(), SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setMenu(R.layout.slideminu);

        ImageView viewById1 = slidingMenu.findViewById(R.id.slid_img);
        /**
         * 设置头像
         */
        String imgtx = user.getString("imgtx", "//storage/emulated/0/Android/data/com.bw.task/files/Pictures/1625282117648.jpg");
        viewById1.setImageBitmap(BitmapFactory.decodeFile(imgtx));
        //头像
        slidingMenu.findViewById(R.id.slid_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                slidimg = slidingMenu.findViewById(R.id.slid_img);
                PictureSelector.create(getActivity(),PictureSelector.SELECT_REQUEST_CODE).selectPicture(true,200,200,1,1);
            }
        });
        ImageView imageView = slidingMenu.findViewById(R.id.xml);
        Glide.with(this).load(R.drawable.xml).into(imageView);
        //用户名
        TextView viewById = slidingMenu.findViewById(R.id.slidname);
        viewById.setText(name);
        slidingMenu.findViewById(R.id.cz).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), PayActivity.class));
            }
        });
        this.money = slidingMenu.findViewById(R.id.money);
        String umoney = user.getString("money", "");
        float v = Float.parseFloat(umoney);
        slidmoney=v;

        this.money.setText(fmoney+"  余额");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(OneFragment.this)) {
            EventBus.getDefault().unregister(this);
        }
        GSYVideoManager.releaseAllVideos();
    }
    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
//        GSYVideoManager.onResume();
    }


}